home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 8_5.lha / 8_5 / extbuf.h < prev    next >
C/C++ Source or Header  |  1993-08-08  |  2KB  |  80 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / class "extensible array"
  6. / This class maintains a character array
  7. / which dynamically lengthens. The array
  8. / begins with a fixed size allocated statically,
  9. / but goes into the heap when the bounds
  10. / of that array are exceeded.
  11. include <string.h>
  12.  
  13. onst int extstartsize = 50;    // initial size of buffer
  14.  
  15. lass extarray
  16.  
  17.    char buf[extstartsize];    // starting buffer
  18.    char *base;            // ptr to current buffer
  19.    char *end;            // end of current buffer
  20.    char *p;            // current location
  21.    int cursize;        // size of current buffer
  22.  
  23. ublic:
  24.    // Initialize the pointers
  25.    // and the static array.
  26.    extarray()
  27. {
  28. base = p = buf;
  29. end = base + extstartsize;
  30. cursize = extstartsize;
  31. }
  32.  
  33.    // If there is a dynamic
  34.    // array, delete it.
  35.    ~extarray()
  36. {
  37. if (base != buf)
  38.     delete base;
  39. }
  40.  
  41.    // Add a character to the array.
  42.    // If it won't fit (along with
  43.    // the null byte) lengthen the
  44.    // array, going into heap memory
  45.    // when necessary.
  46.    void add(char c)
  47. {
  48. *p++ = c;
  49.  
  50. if (p == end)
  51.     {
  52.     char *svp = p;
  53.     char *svbase = base;
  54.     base = new char[cursize + extstartsize];
  55.     memcpy(base, svbase, cursize);
  56.     cursize += extstartsize;
  57.     end = base + cursize;
  58.     p = base + (svp - svbase);
  59.  
  60.     if (svbase != buf)
  61.     delete svbase;
  62.     }
  63. }
  64.  
  65.    // return the current value
  66.    char *val()
  67.        {
  68. *p = '\0';
  69. return base;
  70. }
  71.  
  72.    // Reset the current pointer to the 
  73.    // beginning of the array so that it
  74.    // can be reused.
  75.    void reset()
  76. {
  77. p = base;
  78. }
  79. ;
  80.